package com.nd.android.musicboxlibrary.ui.mymusic.downloadmusic;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.common.utils.StarAppUtils;
import com.nd.android.musicboxlibrary.R;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.adapter.MyMusicDownLoadAdapter;
import com.nd.android.musicboxlibrary.ui.common.BaseFragmentActivity;
import com.nd.android.musicboxlibrary.ui.common.UnMixable;
import com.nd.android.musicboxlibrary.ui.common.ViewInjectorWithReflect;
import com.nd.android.musicboxlibrary.ui.player.PlayerActivity;
import com.nd.android.musicboxlibrary.util.ConfigHelper;
import com.nd.android.musicboxlibrary.util.Log;
import com.nd.android.musicboxlibrary.util.MusicBoxUtils;
import com.nd.android.musicboxlibrary.util.NdTask;
import com.ngds.library.downloadcenter.DownloadChangeObserver;
import com.ngds.library.downloadcenter.Downloads;
import com.squareup.otto.Subscribe;
import org.w3c.dom.Text;

/**
 * <br>
 * Created 2014年7月5日 下午4:11:54
 * 
 * @author 慕容秋
 * @see
 */

public class MyMusicDownloadActivity extends BaseFragmentActivity {

    private int lstSum;

    private static final String CLASS_NAME = "jay_my_download";

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:51:58
     * 
     * @param event MenuPositionEvent
     * @author wat.ztag
     */
    @Subscribe
    public void selectionByPosition(MenuPositionEvent event) {
        int sum = ConfigHelper.getInstance(this).loadIntKey(
                ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, 0);
        if (sum < lstSum) {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
            } else if (holder.lst.getLastVisiblePosition() - 1 == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        } else {
            if (holder.lst.getLastVisiblePosition() == event.mPosition) {
                // holder.lst.setSelection(holder.lst.getFirstVisiblePosition() + 1);
                Log.i(event.toString());
            }
        }
    }

    private List<MusicInfo> singles = new ArrayList<MusicInfo>();

    private MyMusicDownLoadAdapter mAdapter = null;

    private ViewHolder holder = new ViewHolder();

    private TextView tvFooter;

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:52:05
     * 
     * @version MyMusicDownloadActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class ViewHolder implements UnMixable {
        ListView lst;
        LinearLayout pnlRandomPlayer;

        /**
         * 
         * <br>
         * Created 2014年10月7日 下午10:08:28
         * 
         * @param list ListView
         * @author       wat.ztag
        */
        void setLst(ListView list) {
            this.lst = list;
        }

        /**
         * 
         * <br>
         * Created 2014年10月7日 下午10:08:31
         * 
         * @param randomPlayer LinearLayout
         * @author       wat.ztag
        */
        void setPnlRandomPlayer(LinearLayout randomPlayer) {
            this.pnlRandomPlayer = randomPlayer;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mbx_my_music_download_activity);
        ViewInjectorWithReflect.injectView(holder, this);
        initData();
        setupView();
        addListeners();
    }

    private MyDownloadChangeObserver downloadChangeObserver = new MyDownloadChangeObserver(
            new Handler());

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:52:10
     * 
     * @version MyMusicDownloadActivity
     * @author wat.ztag
     * 
     * @see
     */
    class MyDownloadChangeObserver extends DownloadChangeObserver {

        /**
         * Creates a new instance of MyDownloadChangeObserver. <br>
         * Created 2014年9月11日 下午11:52:14
         * 
         * @param handler Handler
         */
        public MyDownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        protected void updateView(boolean selfChange) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        BusProvider.getInstance().register(this);

        getContentResolver().registerContentObserver(Downloads.Impl.CONTENT_URI, true,
                downloadChangeObserver);
        
    }

    @Override
    protected void onPause() {
        super.onPause();

        BusProvider.getInstance().unregister(this);

        getContentResolver().unregisterContentObserver(downloadChangeObserver);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:52:23
     * 
     * @author wat.ztag
     */
    private void setupView() {
        txtTitle.setText(R.string.mbx_music_download);
        setRightButton(R.drawable.mbx_btn_close_selector);
        LinearLayout footView = (LinearLayout) getLayoutInflater().inflate(
                R.layout.mbx_my_music_download_footer, null, false);
        tvFooter = (TextView) footView.findViewById(R.id.tvFooter);
        tvFooter.setVisibility(View.GONE);
        mAdapter = new MyMusicDownLoadAdapter(this, tvFooter);
        holder.lst.addFooterView(footView, null, false);
        holder.lst.setAdapter(mAdapter);
        StarAppUtils.setViewTypeFace(tvFooter, false);
        StarAppUtils.setViewTypeFace((TextView)findViewById(R.id.txtPlayType), false);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:52:27
     * 
     * @author wat.ztag
     */
    protected void initData() {
        new GetMusicListTask(this, R.string.mbx_runing).execute();
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:52:31
     * 
     * @author wat.ztag
     */
    private void addListeners() {
        holder.lst.setOnItemClickListener(mAdapter);
        holder.pnlRandomPlayer.setOnClickListener(this);

        holder.lst.setOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
            }

            @Override
            public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
                lstSum = arg2;
                int sum = ConfigHelper.getInstance(getApplicationContext()).loadIntKey(
                        ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2 + 1);
                if (arg2 < sum && arg2 != 0) {
                    ConfigHelper.getInstance(getApplicationContext()).saveIntKey(
                            ConfigHelper.CONFIG_KEY_LIST_SUM + CLASS_NAME, arg2);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.pnlRandomPlayer) {
            if (singles != null && singles.size() != 0) {
                ManagerFactory.getPlayerInstance().playByRandom(this, singles);
            } else {
                Toast.makeText(this, R.string.mbx_no_music, Toast.LENGTH_LONG).show();
            }

        } else if (id == R.id.btnRight) {
            PlayerActivity.removeSubActivity();
            finish();

        }

        super.onClick(v);
    }

    /**
     * 
     * <br>
     * Created 2014年9月11日 下午11:51:42
     * 
     * @version MyMusicDownloadActivity
     * @author wat.ztag
     * 
     * @see
     */
    private class GetMusicListTask extends NdTask {

        /**
         * Creates a new instance of GetMusicListTask. <br>
         * Created 2014年9月11日 下午11:51:54
         * 
         * @param context Context
         * @param resId int
         */
        public GetMusicListTask(Context context, int resId) {
            super(context, resId);
        }

        @Override
        protected void doSuccess(Object result) {
            singles = (List<MusicInfo>) result;
            if(singles != null && !singles.isEmpty()){
            	List<MusicInfo> tempList = new ArrayList<MusicInfo>();
            	tempList.addAll(singles);
            	for(MusicInfo mi : tempList){
            		if((mi.getSizeDownLoaded() == mi.getSize()
            				&& !(new File(mi.getMusicTemp()).exists() || new File(mi.getHQMusicTemp()).exists())
            				&& !(new File(mi.getMusicPath()).exists() || new File(mi.getHQMusicPath()).exists()))){
            			//该音乐文件已经被手动删除
            			//修复 BUG #62634 【我的音乐盒】手动去SD卡删除一个音乐文件，然后到下载歌曲列表，查看列表，被手动删除的歌曲还存在列表中！
            			singles.remove(mi);
            			ManagerFactory.getDownloadInstance(mContext).removeMusicFromDownloadList(mi);
            		}
            	}
            }
            mAdapter.setDatas(singles);
            tvFooter.setVisibility(View.VISIBLE);
            tvFooter.setText(MusicBoxUtils.getDownloadFooterText(MyMusicDownloadActivity.this,
                    singles));
        }

        @Override
        protected void doFail(NdException result) {
            Toast.makeText(mContext, result.getSimpleMsg(), Toast.LENGTH_LONG).show();

        }

        @Override
        protected Object doInBackground(Object... params) {
            return ManagerFactory.getPlaylistInstance(getApplicationContext())
                    .getMusicListOfDownLoad();
        }

    }
}
